#include "ThrPool.h"

namespace ThrPool
{
SDL_Thread *controlEntityThread = NULL;
bool quit = false;
bool running = false;
Objects::Objects *objects = NULL;

void startControlThread(Objects::Objects *o)
{
	objects = o;
	running = true;
	quit = false;
	controlEntityThread = SDL_CreateThread(control, NULL);
}

void quitEntityThread()
{
	if (running)
	{
		quit = true;

		int threadReturn = 0;
		// wait for thread

		if (controlEntityThread != NULL)
		{
			SDL_WaitThread(controlEntityThread, &threadReturn);
#ifdef _DEBUG
			std::cout << "THREADS: Control thread with TID " << SDL_ThreadID() << " stopped!" << std::endl;
#endif
		}
		else
			std::cerr << "THREADS: No control thread created!" << std::endl;

		running = false;
	}
}

int control(void *data)
{
	// create new timer
	Timer t;
	unsigned int dClock;

	while (quit == false)
	{
		t.update();
		dClock = t.getDeltaClockMs();

		//Cap the update rate
		if (dClock < 1000 / CONTROL_PER_SECOND)
		{
			SDL_Delay((1000 / CONTROL_PER_SECOND) - dClock);
		}

		if (objects != NULL)
			objects->control(0);
	}

	return SDL_ThreadID();

}

void killEvents()
{
	running = false;
	quit = true;
	SDL_KillThread(controlEntityThread);
}

bool isRunning()
{
	return running;
}
}
